// ignore_for_file: file_names, slash_for_doc_comments, must_call_super, unnecessary_overrides, override_on_non_overriding_member, must_be_immutable, prefer_const_constructors, sized_box_for_whitespace, avoid_unnecessary_containers, avoid_print

import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:mybase/base/abstract/IFFR.dart';
import 'package:mybase/base/abstract/IFFRefresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/tool/entitylog/MyEntityTestRun.dart';
import 'package:mybase/base/tool/entitylog/MyLanguageTestRun.dart';
import 'package:mybase/base/tool/file/FFDirectory.dart';
import 'package:mybase/base/tool/file/FFile.dart';
import 'package:mybase/base/widget/layout/FFLineContainer.dart';
import 'package:mybase/base/widget/layout/FFTextButton.dart';
import 'package:mybase/base/widget/page/FFScaffold.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:webview_window_example/config/ConfigVal.dart';
import 'package:webview_window_example/entity/TranslateEntity.dart';
import 'package:webview_window_example/utils/CommonUtils.dart';
import 'package:webview_window_example/utils/navi/AppNavi.dart';

/**
 * 根据flutter项目，以zh-Hans.json为基础，生成指定的其他语言的json，
 * zh-Hans.json所有字段，在其他json中没有的话，就会被上。有的话，保持不变
 */
class CompleteLanguageJsonPage extends FFScaffold {
  String? name;

  CompleteLanguageJsonPage({
    Key? key,
    this.name,
  }) : super(key: key);

  @override
  CompleteLanguageJsonPageState createState() =>
      CompleteLanguageJsonPageState();
}

class CompleteLanguageJsonPageState extends FFScaffoldState with MFFScaffold {
  /**固定写法 */
  @override
  IFFScaffold get iffScaffold => this;

  @override
  CompleteLanguageJsonPage get widget =>
      super.widget as CompleteLanguageJsonPage;

  @override
  IFFRefresh? get iffRefresh => refresh;
  late CompleteLanguageJsonPageRefresh refresh =
      CompleteLanguageJsonPageRefresh(state: this);

  /**固定写法end */
  ScrollController controller = ScrollController();

  String initTargetDirPath = ConfigVal.osDir;
  String? enJsonDir;
  String? languageEntityDir;
  String? exeResultStr = "";

  @override
  void ffInitState() {
    super.ffInitState();
  }

  @override
  Widget? ffNavi(BuildContext context) {
    return AppNavi.createNavi(
      context,
      title: "补全其他语言的key",
    );
  }

  @override
  Widget? ffBody(BuildContext context) {
    return FFLineContainer(
      direction: Axis.vertical,
      padding: EdgeInsets.symmetric(horizontal: 10),
      children: [
        FFTextButton(
          unconstrainedBox: true,
          text: "选择zh-Hans.json所在的目录",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {
            String? selectedDirectory = await FilePicker.platform
                .getDirectoryPath(initialDirectory: initTargetDirPath);

            if (!(await FFDirectory.isExistDirectory(
                selectedDirectory ?? ""))) {
              SmartDialog.showToast("目录选择失败");
              return;
            }
            enJsonDir = selectedDirectory;
            setState(() {});
          },
        ),
        FFTextButton(
          text: enJsonDir,
          maxLines: 1000,
        ),
        FFTextButton(
          unconstrainedBox: true,
          text: "LanguageEntity所在的目录",
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          color: Colors.red,
          margin: EdgeInsets.only(top: 8),
          onClick: () async {
            String? selectedDirectory = await FilePicker.platform
                .getDirectoryPath(initialDirectory: initTargetDirPath);

            if (!(await FFDirectory.isExistDirectory(
                selectedDirectory ?? ""))) {
              SmartDialog.showToast("目标目录选择失败");
              return;
            }

            languageEntityDir = selectedDirectory;
            setState(() {});
          },
        ),
        FFTextButton(
          text: languageEntityDir,
          maxLines: 1000,
        ),
        FFTextButton(
            unconstrainedBox: true,
            text: "创建",
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            color: Colors.red,
            margin: EdgeInsets.only(top: 8),
            onClick: createHandle),
        Container(
          width: 600,
          height: 300,
          color: Colors.grey,
          child: SingleChildScrollView(
            controller: controller,
            child: FFTextButton(
              text: exeResultStr,
              maxLines: 1000,
            ),
          ),
        ),
      ],
    );
  }

  createHandle() async {
    if (!(await FFDirectory.isExistDirectory(enJsonDir ?? ""))) {
      SmartDialog.showToast("zh-Hans.json所在的目录为空");
      return;
    }

    if (!(await FFDirectory.isExistDirectory(languageEntityDir ?? ""))) {
      SmartDialog.showToast("语言实体所在的目录为空");
      return;
    }

    exeResultStr = "";
    setState(() {});

    List<String> languages = [];
    for (int i = 0; i < entitys.length; i++) {
      TranslateEntity entity = entitys[i];
      languages.add(entity.code);
    }

    for (int i = 0; i < languages.length; i++) {
      String code = languages[i];

      String result = await MyLanguageTestRun.createLanguageCodeStr(
        templateFile: "${enJsonDir}/zh-Hans.json",
        targetFile: "${enJsonDir}/${code}.json",
      );
      exeResultStr = "${exeResultStr}\n${result}\n";
    }

    String allJsonStr = await FFile.readAsString("${enJsonDir}/zh-Hans.json");
    Map<String, dynamic> map = json.decode(allJsonStr);

    String result = await MyEntityTestRun.createEntityCodeStr(
        map: map,
        targetDir: "$languageEntityDir",
        entityClassName: "LanguageEntity",
        forceFlush: true);

    exeResultStr = "${exeResultStr}\n${result}\n\n执行完成";
    setState(() {});
    SmartDialog.showToast("执行完成,请查看结果");
  }
}

class CompleteLanguageJsonPageRefresh with MFFRefresh {
  CompleteLanguageJsonPageState state;

  CompleteLanguageJsonPageRefresh({required this.state});

  @override
  bool? ffCanRefreshHead() {
    return true;
  }

  @override
  ffRefresh(bool isHead) {
    ffRefreshResult(isHead, test, state);
  }

  //具体请求业务
  Future<IFFR> test(IRefreshParam? iRefreshParam) async {
    List? list;
    await Future.wait([
      //HomeApi.index_recentlyPlayed(),
    ]).then((value) {
      list = value;
    });

    IFFR? r = list?.safeValue(0);
    return r ?? R(rStatus: RStatus.result);
  }
}
